package com.cql.service.business.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cql.common.constant.HttpStatus;
import com.cql.common.core.DO.MaterialDO;
import com.cql.common.core.DTO.MaterialDTO;
import com.cql.common.exception.CustomException;
import com.cql.common.utils.StringUtils;
import com.cql.mapper.MaterialMapper;
import com.cql.service.business.MaterialService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author cql
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, MaterialDO> implements MaterialService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MaterialMapper materialMapper;

    @Override
    public void insertMaterials(List<MaterialDTO> materials, Integer type, Long menuId) {
        if (StringUtils.isNotEmpty(materials)) {
            if (StringUtils.isNull(menuId)) {
                throw new CustomException(HttpStatus.InnerError.getMessage());
            }
            List<MaterialDO> list = new ArrayList<>();
            for (MaterialDTO material : materials) {
                MaterialDO materialDO = new MaterialDO();
                materialDO.setMenuId(menuId);
                materialDO.setType(type);
                materialDO.setName(material.getName());
                materialDO.setWeight(material.getWeight());
                list.add(materialDO);
            }
            saveBatch(list);
        }

    }

    @Override
    public void deleteMaterial(Long menuId) {
        if (StringUtils.isNotNull(menuId)) {
            UpdateWrapper<MaterialDO> wrapper = new UpdateWrapper<>();
            wrapper.eq("menu_id", menuId);
            materialMapper.delete(wrapper);
        }
    }

    @Override
    public List<MaterialDTO> listMaterial(Long menuId, Integer type) {
        List<MaterialDTO> result = new ArrayList<>();

        QueryWrapper<MaterialDO> wrapper = new QueryWrapper<>();
        wrapper.eq("menu_id", menuId);
        wrapper.eq("type", type);

        List<MaterialDO> materialDOS = materialMapper.selectList(wrapper);

        for (MaterialDO materialDO : materialDOS) {

            MaterialDTO m = new MaterialDTO();
            m.setName(materialDO.getName());
            m.setWeight(materialDO.getWeight());

            result.add(m);
        }

        return result;
    }

}
